<script setup lang="ts">
import { Message } from "@arco-design/web-vue";
import {
  type ColProps,
  TableRowSelection,
  TableColumn,
} from "@arco-design/web-vue";
import { onMounted, reactive, ref, computed } from "vue";
import { tableBorder } from "@/utils/border/table-border.ts";
import {
  expertListApi,
  expertDeleteApi,
  downLoad,
} from "@/services/expertManagement";
import type {
  ExpertListType,
  ExpertAddType,
  ExpertUpdateType,
} from "@/types/expertManagement";
import ExpertManagementForm from "./expertManagementForm.vue";
import useModal from "@/hooks/useModal.ts";
import { getBaseURL, downloadFile } from "@/utils";
const { ModalShow, ModalHide } = useModal();

const colProps: ColProps = {
  xs: 24,
  sm: 24,
  md: 12,
  lg: 6,
  xl: 6,
  xxl: 6,
  span: 6,
};

const rowSelection: TableRowSelection = {
  type: "checkbox",
  showCheckedAll: true,
  onlyCurrent: false,
};

const loading = reactive({
  search: false, // 查询按钮的 Loading
  reset: false, // 重置按钮的 Loading
  import: false, // 导入按钮的 Loading
  export: false, // 导出按钮的 Loading
  downloadTemplate: false, // 裁判模板下载按钮的 Loading
  print: false, // 打印按钮的 Loading
  batchDelete: false, // 批量删除的 Loading
  deleteAll: false, // 全部删除的 Loading
  table: false,
  edit: false,
  delete: false,
});

const selectedKeys = ref<string[]>([]);

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: true,
});

const centerContent = ref<{
  show: () => void;
  edit: (data: ExpertListType) => void;
  info: (data: ExpertListType) => void;
}>();

// 查询
const handleSearch = () => {
  pagination.current = 1;
  selectedKeys.value = [];
  getList();
};
// 重置
const handleReset = () => {
  searchValue.trueName = "";
  handleSearch();
};
// 添加
const handleAdd = () => {
  options.title = "添加专家";
  centerContent.value?.show();
};
// 批量删除
const handleBatchDelete = () => {
  const id = selectedKeys.value.join(",");
  ModalShow({
    content: "您确认要删除选中的专家信息吗？",
  })
    .then(() => {
      expertDeleteApi({
        id: id,
      }).then((res) => {
        if (res.code === 200) {
          if (data.value.length === 1) {
            pagination.current = pagination.current - 1;
          }
          getList();
          ModalHide();
          Message.success("删除成功");
        } else {
          ModalHide();
        }
      });
    })
    .finally(() => {
      loading.deleteAll = false;
    });
};

// 全部删除
const handleAllDelete = () => {
  if (pagination.total === 0) {
    return; // 如果没有数据，则不执行删除操作
  }
  loading.deleteAll = true;
  const id = data.value.map((item) => item.id).join(",");

  ModalShow({
    content: "您确认要删除全部专家信息吗？",
  })
    .then(() => {
      expertDeleteApi({
        id: id,
      }).then((res) => {
        if (res.code === 200) {
          if (data.value.length === 1) {
            pagination.current = pagination.current - 1;
          }
          getList();
          ModalHide();
          Message.success("删除成功");
        } else {
          ModalHide();
        }
      });
    })
    .finally(() => {
      loading.deleteAll = false;
    });
};

// 导入
const handleImport = () => {};

// 模板下载
const handleDownloadTemplate = () => {
  downLoad({ templateName: "teacher" }).then((res) => {
    downloadFile(res as Blob, `专家导入模板.xlsx`);
  });
};
// 打印
const handlePrint = () => {};
// 分页
const handlePageChange = (page: number) => {
  pagination.current = page;
  getList();
};
// 编辑
const handleEdit = (res: ExpertListType) => {
  options.title = "编辑专家";
  centerContent.value?.edit(res);
};

const handleInfo = (res: ExpertListType) => {
  options.title = "专家详情";
  centerContent.value?.info(res);
};

// 删除
const handleDelete = (res: ExpertListType) => {
  ModalShow({
    content: "您确认要删除这条专家信息吗？",
  })
    .then(() => {
      expertDeleteApi({
        id: res.id,
      }).then((res) => {
        if (res.code === 200) {
          if (data.value.length === 1) {
            pagination.current = pagination.current - 1;
          }
          getList();
          ModalHide();
          Message.success("删除成功");
        } else {
          ModalHide();
        }
      });
    })
    .finally(() => {
      loading.delete = false;
    });
};

const data = ref<ExpertListType>([]);
const searchValue = reactive({
  trueName: "",
});
const getList = () => {
  expertListApi({
    current: pagination.current,
    size: pagination.pageSize,
    trueName: searchValue.trueName,
  }).then((res) => {
    data.value = res.data.records;
    pagination.total = res.data.total;
    pagination.current = res.data.current;
    pagination.pageSize = res.data.size;
  });
};

const options = reactive({
  title: "",
});

const columns: TableColumn[] = [
  {
    title: "序号",
    dataIndex: "index",
    width: 80,
    slotName: "index",
    align: "center",
  },
  {
    title: "账号",
    key: "name",
    dataIndex: "name",
    align: "center",
  },
  {
    title: "姓名",
    key: "trueName",
    dataIndex: "trueName",
    align: "center",
  },
  {
    title: "电话",
    key: "phone",
    dataIndex: "phone",
    align: "center",
  },
  {
    title: "来源",
    key: "city",
    dataIndex: "city",
    align: "center",
  },
  {
    title: "领域",
    key: "channel",
    dataIndex: "channel",
    align: "center",
  },
  {
    title: "单位",
    key: "unit",
    dataIndex: "unit",
    align: "center",
  },
  {
    title: "职务",
    key: "post",
    dataIndex: "post",
    align: "center",
  },
  {
    title: "职称",
    key: "title",
    dataIndex: "title",
    align: "center",
  },
  {
    title: "操作",
    slotName: "operate",
    align: "center",
    width: 160,
    fixed: "right",
  },
];

const headers = {
  token: localStorage.getItem("token")!,
};

const actions = computed(() => {
  return getBaseURL() + "teacher/importXls";
});

// 上传文件前的验证
const beforeUpload = (file: any) => {
  const isExcel = [
    "application/vnd.ms-excel",
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  ].includes(file.type);
  if (!isExcel) {
    Message.error("只能上传 Excel 文件!");
    return false; // 阻止上传
  }
  return true; // 允许上传
};

// 上传成功后
const success = (options: { file: any; event?: ProgressEvent }) => {
  const res = options.response;

  if (res.code === 200) {
    Message.success(res.msg);
  } else {
    if (res.data) {
      // if (res.data !== null) {
      if (res.data.errors) {
        return Message.error(JSON.stringify(res.data.errors));
      }
      Message.warning(res.msg);
    } else {
      Message.warning(res.msg);
    }
  }
  getList();
  return false;
};

onMounted(() => {
  getList();
});
</script>

<template>
  <a-space
    class="container"
    direction="vertical"
  >
    <a-card>
      <a-form>
        <a-row :gutter="24">
          <a-col v-bind="colProps">
            <a-form-item label="姓名">
              <a-input
                allow-clear
                v-model="searchValue.trueName"
                placeholder="请输入姓名"
              />
            </a-form-item>
          </a-col>
          <a-col v-bind="colProps">
            <a-form-item :label-col-props="{span: 0}">
              <a-space>
                <a-button
                  type="primary"
                  @click="handleSearch"
                  :loading="loading.search"
                >
                  <template #icon>
                    <icon-search />
                  </template>
                  <span>查询</span>
                </a-button>
                <a-button
                  @click="handleReset"
                  :loading="loading.reset"
                >
                  <template #icon>
                    <icon-refresh />
                  </template>
                  <span>重置</span>
                </a-button>
              </a-space>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <a-card>
      <div class="tabletools">
        <a-space>
          <a-button
            type="outline"
            @click="handleAdd"
          >新增</a-button>
          <a-button
            type="outline"
            :loading="loading.batchDelete"
            status="danger"
            @click="handleBatchDelete"
            :disabled="selectedKeys.length === 0"
          >批量删除</a-button>
          <a-button
            type="outline"
            :loading="loading.deleteAll"
            status="danger"
            @click="handleAllDelete"
          >全部删除</a-button>

          <a-upload
            :action="actions"
            :headers="headers"
            @before-upload="beforeUpload"
            :show-file-list="false"
            @success="success"
          >
            <template #upload-button>
              <a-button
                type="outline"
                @click="handleImport"
                :loading="loading.import"
              >导入</a-button>
            </template>
          </a-upload>

          <a-button
            type="outline"
            @click="handleDownloadTemplate"
            :loading="loading.downloadTemplate"
          >专家模板下载</a-button>
        </a-space>
      </div>

      <a-table
        row-key="id"
        :loading="loading.table"
        :data="data"
        :columns="columns"
        :bordered="tableBorder"
        :pagination="pagination"
        @page-change="handlePageChange"
        :row-selection="rowSelection"
        v-model:selected-keys="selectedKeys"
      >
        <template #index="{rowIndex}">
          {{ (pagination.current - 1) * pagination.pageSize + rowIndex + 1 }}
        </template>

        <template #operate="{ record }">
          <a-space>
            <a-button
              type="primary"
              @click="handleInfo(record)"
            >详情</a-button>
            <a-button
              type="primary"
              @click="handleEdit(record)"
              :loading="loading.edit"
            >编辑</a-button>
            <a-button
              type="primary"
              status="danger"
              @click="handleDelete(record)"
              :loading="loading.delete"
            >删除</a-button>
          </a-space>
        </template>
      </a-table>
    </a-card>
  </a-space>

  <expert-management-form
    ref="centerContent"
    @list="getList"
    :title="options.title"
  />
</template>

<style scoped lang="scss">
</style>